﻿<script setup lang="ts" name="EChart">
import * as echarts from 'echarts'
import 'echarts-gl'
import type { EChartsOption, ECharts } from 'echarts'
import { debounce } from 'lodash-es'
import { PropType } from 'vue'
import { templateRef, useResizeObserver, useDebounceFn } from '@vueuse/core'

const { getPrefixCls } = useDesign()

const prefixCls = getPrefixCls('echart')

const props = defineProps({
  options: {
    type: Object as PropType<EChartsOption>,
    required: true
  }
})

const elRef = ref<ElRef>()

let echartRef: Nullable<ECharts> = null

watch(
  () => props.options,
  (options) => {
    if (options) {
      console.log(options)
      if (echartRef) {
        echartRef?.setOption(options)
      } else {
        if (unref(elRef)) {
          echartRef = echarts.init(unref(elRef) as HTMLElement)
          echartRef?.setOption(options)
        }
      }
    }
  },
  {
    immediate: true,
    deep: true
  }
)

const resizeHandler = debounce(() => {
  if (echartRef) {
    echartRef.resize()
  }
}, 100)

const elRefDom = templateRef<HTMLElement | null>('elRef', null)

// 监听元素尺寸变化
useResizeObserver(
  elRefDom,
  useDebounceFn(() => {
    resizeHandler()
  }, 200)
)

onMounted(() => {
  window.addEventListener('resize', resizeHandler)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeHandler)
})

onActivated(() => {
  if (echartRef) {
    echartRef.resize()
  }
})
</script>

<template>
  <div ref="elRef" :class="[$attrs.class, prefixCls]" />
</template>

<style scoped lang="scss">
$prefix-cls: #{$namespace}-echart;

.#{$prefix-cls} {
  width: 100%;
  flex: 1;
}
</style>
